package com.gxuwz.attend.web.servlet.instructor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gxuwz.attend.context.AppContext;
import com.gxuwz.attend.entity.Course; // 引入 Course 实体类
import com.gxuwz.attend.service.instructor.CourseService; // 修改为 CourseService
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.List;

@WebServlet("/instructor/courses") // 修改 URL 映射
public class CourseServlet extends HttpServlet {

    private CourseService courseService; // 修改为 CourseService
    private final ObjectMapper objectMapper = new ObjectMapper();


    @Override
    public void init() throws ServletException {
        super.init();
        courseService = AppContext.getBean(CourseService.class); // 修改为 CourseService
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name = request.getParameter("name");
        String id = request.getParameter("id");

        int page = Integer.parseInt(request.getParameter("page"));
        int size = Integer.parseInt(request.getParameter("size"));
        int offset = (page - 1) * size;

        List<Course> coursesList = courseService.getAllCourses(id, name, size, offset); // 修改为 getAllCourses
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");

        String json = objectMapper.writeValueAsString(coursesList);
        response.getWriter().write(json);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Course course = objectMapper.readValue(request.getInputStream(), Course.class); // 修改为 Course
        courseService.addCourse(course); // 修改为 addCourse
        response.setStatus(HttpServletResponse.SC_CREATED); // 201 Created
    }

    @Override
    protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Course course = objectMapper.readValue(request.getInputStream(), Course.class); // 修改为 Course
        courseService.updateCourse(course); // 修改为 updateCourse
        response.setStatus(HttpServletResponse.SC_OK); // 200 OK
    }

    @Override
    protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String courseID = request.getParameter("courseID"); // 修改为 courseID
        courseService.deleteCourse(courseID); // 修改为 deleteCourse
        response.setStatus(HttpServletResponse.SC_NO_CONTENT); // 204 No Content
    }
}
